package mn.idax.exchange.otc.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mn.idax.exchange.auth.bean.AuthInfo;
import mn.idax.exchange.auth.util.AuthInfoUtils;
import mn.idax.exchange.common.bean.ResponseData;
import mn.idax.exchange.otc.annotation.LoginAuth;
import mn.idax.exchange.otc.constant.RequestUrlConstant;
import mn.idax.exchange.otc.domain.MessageNotifyPageDTO;
import mn.idax.exchange.otc.domain.MessageNotifyPagePCDTO;
import mn.idax.exchange.otc.domain.OrderChat;
import mn.idax.exchange.otc.domain.UpdateMessage;
import mn.idax.exchange.otc.enums.MessageNotifyEnum;
import mn.idax.exchange.otc.enums.MessageTypeEnum;
import mn.idax.exchange.otc.enums.response.MessageTypeError;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.service.MessageService;
import mn.idax.exchange.otc.service.MongoMessageNotifyService;
import mn.idax.exchange.otc.util.LogUtils;
import mn.idax.exchange.otc.util.ParamUtils;
import mn.idax.exchange.otc.vo.MessageDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * @Auther: dison
 * @Date: 2018/9/10 17:18
 * @Description:
 */
@Api(value = "我的通知",tags = {"我的通知"})
@RequestMapping(RequestUrlConstant.MODULE_NOTIFY)
@RestController
public class MyNotifyController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyNotifyController.class);

    /**
     * 极光推送模板支持的语言
     */
    private static final String[] SUPPORT_LANG ={"zh_cn","en_us","ja_jp","ko_kr","zh_tw"};

    @Autowired
    private MongoMessageNotifyService mongoMessageNotifyService;

    @Autowired
    private MessageService messageService;

    @PostMapping(RequestUrlConstant.NOTIFY_UNREAD)
    @ApiOperation(value = "获取我的未读条数", notes = "获取我的未读条数")
    public ResponseData getUnReadNum(){
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        return ResponseData.success(this.mongoMessageNotifyService.queryAllMessageByUserId(userId));
    }

    @PostMapping(RequestUrlConstant.NOTIFY_LIST_PAGE)
    @ApiOperation(value = "分页获取我的所有通知内容", notes = "分页获取我的所有通知内容")
    public ResponseData list(@RequestBody MessageNotifyPageDTO messageNotifyPageDTO){
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        if (messageNotifyPageDTO.getPageSize() == null){
            messageNotifyPageDTO.setPageSize(10);
        }
        if (messageNotifyPageDTO.getCurrentPage() == null){
            messageNotifyPageDTO.setCurrentPage(1);
        }

        return ResponseData.success(this.mongoMessageNotifyService.queryPageMessageById(userId , messageNotifyPageDTO));
    }

    /**
     * 临时为PC加的 后期可能会拿掉
     */
    @PostMapping(RequestUrlConstant.NOTIFY_LIST_PAGE_PC)
    @ApiOperation(value = "PC分页获取我的所有通知内容", notes = "PC分页获取我的所有通知内容")
    public ResponseData listPC(@RequestBody MessageNotifyPagePCDTO messageNotifyPageDTO){
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        if (messageNotifyPageDTO.getPageSize() == null){
            messageNotifyPageDTO.setPageSize(10);
        }
        if (messageNotifyPageDTO.getCurrentPage() == null){
            messageNotifyPageDTO.setCurrentPage(1);
        }
        if (messageNotifyPageDTO.getMessageType() != null
                &&messageNotifyPageDTO.getMessageType().intValue() != MessageNotifyEnum.MessageType.order.getType()
                && messageNotifyPageDTO.getMessageType().intValue() != MessageNotifyEnum.MessageType.system.getType()){
            throw new IdaxException(MessageTypeError.message_type_error.getRespCode());
        }

        return ResponseData.success(this.mongoMessageNotifyService.queryPagePCMessageById(userId , messageNotifyPageDTO));
    }

    /**
     * 替换语言
     * @param lang
     * @return
     */
    public String replaceLang(String lang){
        for (String s : SUPPORT_LANG) {
            if (s.equals(lang)){
                return lang;
            }
        }
        return "en_us";
    }

    /**
     * 系统消息 app 2.0
     */
    @PostMapping(RequestUrlConstant.FIND_MESSAGE_SYSTEM)
    @ApiOperation(value = "消息中的系统消息", notes = "消息中的系统消息")
    public ResponseData getSystemMessage(HttpServletRequest request){
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
//        Integer userId = 155504;

        LOGGER.info("getSystemMessage are invoke,userid {}",userId);

        String lang = ParamUtils.getLanguageByRequest(request).replace("-","_");

        lang = replaceLang(lang);

        List<MessageDTO> systemMessage = messageService.getSystemMessage(userId, lang);
        return ResponseData.success(systemMessage);
    }

    /**
     * 系统消息 app 2.0
     */
    @PostMapping(RequestUrlConstant.UPDATE_MESSAGE_SYSTEM)
    @ApiOperation(value = "更新系统消息为已读状态", notes = "更新系统消息为已读状态")
    public ResponseData updateSystemMessage(@RequestBody UpdateMessage updateMessage){

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
//        Integer userId = 155501;

        messageService.updateSystemMessage(updateMessage,userId);
        return ResponseData.success();
    }

    /**
     * 聊天消息 app 2.0
     */
    @PostMapping(RequestUrlConstant.FIND_MESSAGE_CHAT)
    @ApiOperation(value = "消息中的聊天消息", notes = "消息中的聊天消息")
    public ResponseData getChatMessage(HttpServletRequest request){

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
//        Integer userId = 155501;

        String lang = ParamUtils.getLanguageByRequest(request).replace("-","_");

        lang = replaceLang(lang);

        List<MessageDTO> chatMessage = messageService.getChatMessage(lang,userId);
        return ResponseData.success(chatMessage);
    }

    /**
     * 系统消息 app 2.0
     */
    @PostMapping(RequestUrlConstant.UPDATE_MESSAGE_CHAT)
    @ApiOperation(value = "更新订单消息为已读状态", notes = "更新订单消息为已读状态")
    public ResponseData updateChatMessage(@RequestBody UpdateMessage updateMessage){

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
//        Integer userId = 155501;

        messageService.updateChatMessage(updateMessage,userId);
        return ResponseData.success();
    }


    /**
     * 消息一键已读 app 2.3
     * app 端传ids来更好,但是数据存放在两个地方
     */
    @PostMapping(RequestUrlConstant.UPDATE_MESSAGE_TO_READ)
    @ApiOperation(value = "消息一键已读", notes = "消息一键已读")
    public ResponseData updateAllMessageToRead(){

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
//        Integer userId = 155501;
        messageService.updateAllMessageToRead(userId);
        return ResponseData.success();
    }


}
